package com.ctrip.demo.leetcode;

public class RemoveListNode2 {

    public static void main(String[] args) {
        System.out.println(removeNthFromEnd(new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5, new ListNode(6))))), 2));

    }


    public static ListNode removeNthFromEnd(ListNode head, int n) {
        return removeNode(head, n) == n ? head.next : head;
    }

    public static int removeNode(ListNode node, int n) {
        // 如果node.next == null 则证明链表只有一个节点
        if (node.next == null) {
            return 1;
        }
        //
        int m = removeNode(node.next, n);
        if (m == n) {
            if (m == 1) {
                node.next = null;
            } else {
                node.next = node.next.next;
            }
        }
        return m + 1;
    }

}
